package com.easyban.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easyban.common.R;
import com.easyban.entity.Product;
import com.easyban.entity.SubCategories;
import com.easyban.service.ProductService;
import com.easyban.service.SubCategoriesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/subCategories")
@Slf4j
public class SubCategoriesController {
    @Autowired
    private SubCategoriesService subCategoriesService;
    @Autowired
    private ProductService productService;

    @PostMapping
    private R<String> addSubCategories(@RequestBody SubCategories subCategories) {
        log.info("subCategories: {}", subCategories);
        subCategoriesService.save(subCategories);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    private R<Page<SubCategories>> getSubCategoriesPage(int page, int pageSize, String name) {
        log.info("分页查询: page: {}, pageSize: {}", page, pageSize);
        //构造分页构造器
        Page<SubCategories> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<SubCategories> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), SubCategories::getName, name);

        queryWrapper.orderByDesc(SubCategories::getParentId);

        subCategoriesService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    @GetMapping("/{id}")
    private R<SubCategories> getSubCategoriesById(@PathVariable Long id) {
        LambdaQueryWrapper<SubCategories> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubCategories::getId, id);
        SubCategories subCategories = subCategoriesService.getOne(queryWrapper);
        return R.success(subCategories);
    }

    @PutMapping
    private R<String> updateSubCategories(@RequestBody SubCategories subCategories) {
        subCategoriesService.updateById(subCategories);
        return R.success("修改成功");
    }

    @DeleteMapping("/{id}")
    private R<String> deleteSubCategories(@PathVariable Long id) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getSubId, id);
        List<Product> list = productService.list(queryWrapper);


        if (list.isEmpty()){
            subCategoriesService.removeById(id);
            return R.success("删除成功");
        }else {
            return R.error("该分类还有商品");
        }


    }

}
